#!/usr/bin/env python
#--*-- coding: UTF-8 --*--

import sys      # 为了参数
import urllib, urllib2  # 发送URL的包
import demjson  # json的解码、编码
import time
import datetime  # 时间
import tempfile, os
from subprocess import call

url = "http://localhost:8080/rest/idea/";
islist = False;

if len(sys.argv) == 1:
    data = {};

    EDITOR = os.environ.get('EDITOR','vim'); #that easy!
    initial_message = ""; # if you want to set up the file somehow
    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        tf.write(initial_message);
        tf.flush();
        call([EDITOR, tf.name]);

        # do the parsing with `tf` using regular File operations.
        # for instance:
        tf.seek(0);
        edited_message = tf.read();
    content = edited_message;

    if content == "":
        print("\t内容为空，不保存");
        exit();

    data['msg'] = content;
    tags = raw_input("请输入标签：");
    data['tags'] = tags;
    url += "create";

    post_data = urllib.urlencode(data);
    req = urllib2.urlopen(url, post_data);
    content = req.read();
    print("%s\n" % (content));
    exit();

elif sys.argv[1] == "--help" or sys.argv[1] == "-h":
    print("\t请输入参数：");
    print("\t\tcontent [tags]");
    print("\t\tlist [number]");
    exit();

elif sys.argv[1] == "list":
    if len(sys.argv) == 2:
        url += "current"
        islist = True;
    else:
        url += "list/" + sys.argv[2]
        islist = True;

elif len(sys.argv) == 2:
    url += "create/" + sys.argv[1];

elif len(sys.argv) >= 3:
    url += "create/" + sys.argv[1] + "/" + sys.argv[2];

# print(url);
# exit();

request = urllib2.Request(url)
respose = urllib2.urlopen(request)

if islist:
    list = demjson.decode(respose.read())

    # for idea in list:
    if list.__len__() == 0:
        print("\t没有任何 idea");
        exit();

    for i in range(0, list.__len__())[::-1]:
        idea = list[i];
        print("\t%d\t%s   %s\t%s" % (idea["id"], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(long(idea["time"])/1000)), idea["tags"], idea["content"]));
